package com.company.woye;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.graphics.Color;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.inputmethod.InputMethodManager;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import androidx.appcompat.app.AppCompatActivity;
import androidx.drawerlayout.widget.DrawerLayout;

import com.company.woye.utils.DBUtil;

import org.json.JSONArray;
import org.json.JSONException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import static android.view.ViewGroup.LayoutParams.MATCH_PARENT;
import static com.company.woye.MyApplication.UrlCut;

public class QueryCutPlanActivity extends AppCompatActivity implements View.OnClickListener {
    private String TAG=this.getClass().getName();
    private final int MSG_DetailOver=1001;
    private final int MSG_HeadOver =1002;
    private final int MSG_GetDetail=1003;
    private final int MSG_OrderOver=1004;
    private final int MSG_DetailHeadOver =1005;
    private final int MSG_SonDetailOver=1006;
    private final int Msg_SetIdentOver=1007;

    private final int MSG_ERROR=9988;

    String STORE_NAME = "Settings";
    String curLoginUserNo,curLoginUser,curServiceUrl="",curServiceDir="",curDepartNo,curDepart,CPUID;
    String QueryTitle,QueryType,MainOpers,SonOpers,masterKeyValue;
    Button btn_Return, btn_filter,btn_Refresh;
    Button btn_ignore,btn_cancelIgnore;
    ListView masterList,detailList;
    TextView txt_Title,tv_filter;
    EditText edt_filter;
    JSONArray masterJson,headJson,detailHeadJson,detailJson;
    Toast curToast;
    String[] mainOper,sonOper;
    String selOrderNo="",selStyleNo="",selStyleSort="",NeedOrder="",NeedFilter="",ManuDepart="",selKeyValue="",selLBDH="";

    LinearLayout querylisthead,detailListhead;
    DrawerLayout drawerLayout;
    private ProgressDialog waitDialog = null;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_cutplan_query);
        hideBottomUIMenu();
        waitDialog= new ProgressDialog(QueryCutPlanActivity.this);
        waitDialog.setTitle(getString(R.string.SystemHint));
        //获取登陆参数
        Bundle paramBundle = this.getIntent().getExtras();
        curLoginUserNo=paramBundle.getString("LoginUserNo");
        curLoginUser=paramBundle.getString("LoginUser");
        curDepartNo=paramBundle.getString("CurDepartNO");
        curDepart=paramBundle.getString("CurDepart");
        curServiceUrl=paramBundle.getString("ServiceUrl");
        curServiceDir=paramBundle.getString("ServiceDir");
        QueryType=paramBundle.getString("QueryType","MUTI");
        NeedOrder=paramBundle.getString("NeedOrder","NO");
        NeedFilter=paramBundle.getString("NeedFilter","NO");
        ManuDepart=paramBundle.getString("ManuDepart","");
        selOrderNo=paramBundle.getString("OrderNo","");
        selStyleNo=paramBundle.getString("StyleNo","");
        selStyleSort=paramBundle.getString("StyleSort","");
        MainOpers=paramBundle.getString("MainOpers","");
        SonOpers=paramBundle.getString("SonOpers","");
        CPUID=paramBundle.getString("CPUID");
        mainOper=MainOpers.split("|");
        sonOper=SonOpers.split("|");
        //界面信息
        QueryTitle=paramBundle.getString("QueryTitle");
        System.out.println(paramBundle);
        //初始化界面
        btn_ignore=findViewById(R.id.btn_ignore);
        btn_ignore.setOnClickListener(this);
        btn_cancelIgnore=findViewById(R.id.btn_cancelIgnore);
        btn_cancelIgnore.setOnClickListener(this);
        btn_ignore.setVisibility(View.GONE);
        btn_cancelIgnore.setVisibility(View.GONE);

        txt_Title=findViewById(R.id.txt_Title);
        txt_Title.setText(QueryTitle);
        btn_Refresh=findViewById(R.id.btn_Refresh);
        btn_Refresh.setOnClickListener(this);
        findViewById(R.id.btn_setIdent).setOnClickListener(this);
        findViewById(R.id.btn_clearIdent).setOnClickListener(this);
        btn_Return=findViewById(R.id.btn_Return);
        btn_Return.setOnClickListener(this);
        masterList =findViewById(R.id.masterList);
        masterList.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                try {
                    if (masterJson.optJSONObject(position).has("IgnoreSign")&&masterJson.optJSONObject(position).has("LBDH")){
                        selLBDH=masterJson.optJSONObject(position).getString("LBDH");
                        if (masterJson.optJSONObject(position).getString("IgnoreSign").equals("Y")){
                            btn_ignore.setVisibility(View.GONE);
                            btn_cancelIgnore.setVisibility(View.VISIBLE);
                        } else {
                            btn_ignore.setVisibility(View.VISIBLE);
                            btn_cancelIgnore.setVisibility(View.GONE);
                        }
                    }
                    if (masterJson.optJSONObject(position).has("KeyValue")) {
                        masterKeyValue=masterJson.optJSONObject(position).getString("KeyValue");
                        GetSonDetail(QueryType,masterKeyValue);
                        drawerLayout.openDrawer(Gravity.RIGHT);
                    } else {
                        curToast.setText("主数据中不包含KeyValue数据,无法调用明细!");
                        curToast.show();
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
        });
        detailList =findViewById(R.id.detailList);
        btn_filter =findViewById(R.id.btn_filter);
        btn_filter.setOnClickListener(this);
        detailList.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                if (detailJson!=null&&detailJson.length()>0){
                    if (detailJson.optJSONObject(position).has("KeyValue")){
                        try {
                            selKeyValue=detailJson.optJSONObject(position).getString("KeyValue");
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                    }
                }
            }
        });
        //列表头;
        querylisthead=findViewById(R.id.querylisthead);
        detailListhead=findViewById(R.id.detailListhead);
        //文本框
        edt_filter = findViewById(R.id.edt_filter);
        tv_filter=findViewById(R.id.tv_filter);
        //初始提醒;
        curToast = Toast.makeText(this, "", Toast.LENGTH_SHORT);
        if (NeedFilter.equals("NO")) {
            edt_filter.setVisibility(View.GONE);
            tv_filter.setVisibility(View.GONE);
            btn_filter.setVisibility(View.GONE);
        }
        //抽屉
        drawerLayout = findViewById(R.id.drawer);

    }

    /**
     * 隐藏虚拟按键，并且全屏
     */
    protected void hideBottomUIMenu() {
        //隐藏状态栏和底部虚拟按键
        View decorView = getWindow().getDecorView();
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
            int flag = View.SYSTEM_UI_FLAG_LAYOUT_STABLE
                    | View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN
                    | View.SYSTEM_UI_FLAG_HIDE_NAVIGATION
                    | View.SYSTEM_UI_FLAG_FULLSCREEN
                    | View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY;
            decorView.setSystemUiVisibility(flag);
        }
    }
    // 隐藏手机键盘
    private void hideIM(View edt) {
        try {
            InputMethodManager im = (InputMethodManager) getApplicationContext().getSystemService(Activity.INPUT_METHOD_SERVICE);
            IBinder windowToken = edt.getWindowToken();
            if (windowToken != null) {
                im.hideSoftInputFromWindow(windowToken, 0);
            }
        } catch (Exception e) {

        }
    }
    public String TransValue(String params)
    {
        if (params.toUpperCase().equals("NULL")||params.equals("0")||params.equals("0.0"))
            return "";
        else return params;
    }

    //字符串加减天数
    private String StringToDate(String time, int AddDays) {
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
        Date date= null;
        try {
            date = format.parse(time);
        } catch (ParseException e) {
            e.printStackTrace();
        }
        Calendar c = Calendar.getInstance();
        System.out.println(date);
        c.setTime(date);
        c.add(Calendar.DAY_OF_MONTH, AddDays);// 今天+1天
        Date tmpDate = c.getTime();
        System.out.println(tmpDate);
        String s = format.format(tmpDate);
        return s;
    }
    @Override
    public void onClick(View v) {
        hideIM(v);
        switch (v.getId()){
            case R.id.btn_Refresh:
                GetHeadList(QueryType);
                GetSonHeadList(QueryType);
                break;
            case R.id.btn_filter:
                GetDetail(QueryType);
                break;
            case R.id.btn_Return:
                finish();
                break;
            case R.id.btn_setIdent:
                setIdent("3");
                break;
            case R.id.btn_clearIdent:
                setIdent("0");
                break;
            case R.id.btn_ignore:
                setIgnore("Y");
                break;
            case R.id.btn_cancelIgnore:
                setIgnore("N");
                break;
            default:
                break;
        }

    }
    private void setIdent(String ident){
        if (selKeyValue.length()==0){
            curToast.setText("请先选择面料！");
            curToast.show();
        }
        String sqlCmd="Exec Agv_Wms_CutPlanSetIdent @OperType='SetIdent', @IdentValue='"+ident
                +"',@KeyValue='" + selKeyValue+"',@UserNo='" + curLoginUserNo + "',@CPUID='" + CPUID + "'";
        ReadSQLData(sqlCmd,null);
    }

    private void setIgnore(String ident){
        if (selKeyValue.length()==0){
            curToast.setText("请先选择面料！");
            curToast.show();
        }
        String sqlCmd="Exec Agv_Wms_CutPlanSetIgnore @OperType='SetIgnore', @IgnoreValue='"+ident
                +"',@LBDH='" + selLBDH+"',@UserNo='" + curLoginUserNo + "',@CPUID='" + CPUID + "'";
        ReadSQLData(sqlCmd,UrlCut);
    }

    @Override
    protected void onResume() {
        super.onResume();
        btn_Refresh.performClick();
    }


    //获取明细;
    private void GetDetail(String paramType) {
        btn_ignore.setVisibility(View.GONE);
        btn_cancelIgnore.setVisibility(View.GONE);
        waitDialog.setMessage("正在加载请稍等.....");
        waitDialog.show();
        selKeyValue="";
        try {
            masterJson = new JSONArray("[]");
            //显示明细数据
            MasterListAdapter masterListAdapter =new MasterListAdapter(getApplicationContext());
            masterList.setAdapter(masterListAdapter);
        } catch (Exception e){
            e.printStackTrace();
        }
        String sqlCmd="Exec Agv_Wms_MutiQuery @OperType='Query',@QueryTitle='"+QueryTitle+"',@QueryType='"+paramType+"',@filter='"+ edt_filter.getText().toString()
                +"',@OrderNo='"+selOrderNo+"',@StyleNo='"+selStyleNo+"',@StyleSort='"+selStyleSort
                +"',@UserNo='" + curLoginUserNo + "',@CPUID='" + CPUID + "'";
        ReadSQLData(sqlCmd,null);

    }

    //获取明细;
    private void GetSonDetail(String paramType, String paramKey) {
        waitDialog.setMessage("正在加载请稍等.....");
        waitDialog.show();
        try {
            detailJson = new JSONArray("[]");
            //显示明细数据
            DetailListAdapter detailListAdapter =new DetailListAdapter(getApplicationContext());
            detailList.setAdapter(detailListAdapter);
        } catch (Exception e){
            e.printStackTrace();
        }
        String sqlCmd="Exec Agv_Wms_MutiQuery @OperType='SonQuery',@QueryTitle='"+QueryTitle+"',@QueryType='"+paramType+"',@WorkDate='"+ edt_filter.getText().toString()
                +"',@OrderNo='"+selOrderNo+"',@StyleNo='"+selStyleNo+"',@StyleSort='"+selStyleSort+"',@KeyValue='"+paramKey
                +"',@UserNo='" + curLoginUserNo + "',@CPUID='" + CPUID + "'";
        ReadSQLData(sqlCmd,null);

    }


    //提交所选择的工序至服务器,然后刷新工序列表;
    private void GetHeadList(final String paramType) {
        try {
            headJson=new JSONArray("[]");
        } catch (JSONException e) {
            e.printStackTrace();
        }
        String sqlcmd="Exec Agv_Wms_MutiQuery @OperType='Title',@QueryTitle='"+QueryTitle+"',@QueryType='"+paramType
                +"',@OrderNo='"+selOrderNo+"',@StyleNo='"+selStyleNo+"',@StyleSort='"+selStyleSort
                +"',@UserNo='" + curLoginUserNo + "',@CPUID='" + CPUID + "'";
        ReadSQLData(sqlcmd,null);
    }


    //提交所选择的工序至服务器,然后刷新工序列表;
    private void GetSonHeadList(final String paramType) {
        try {
            detailHeadJson=new JSONArray("[]");
        } catch (JSONException e) {
            e.printStackTrace();
        }
        String sqlcmd="Exec Agv_Wms_MutiQuery @OperType='SonTitle',@QueryTitle='"+QueryTitle+"',@QueryType='"+paramType
                +"',@OrderNo='"+selOrderNo+"',@StyleNo='"+selStyleNo+"',@StyleSort='"+selStyleSort
                +"',@UserNo='" + curLoginUserNo + "',@CPUID='" + CPUID + "'";
        ReadSQLData(sqlcmd,null);

    }

    //创建列;
    private void CreateListHead() {
        //内容为表头，宽度，自适应;
        if ((headJson != null) && (headJson.length() > 0)) {
            int childCount = querylisthead.getChildCount();
            for (int i = childCount - 1; i >= 0; i--) {
                View view = querylisthead.getChildAt(i);
                if ((view instanceof TextView)||(view instanceof View)) {
                    querylisthead.removeViewAt(i);
                }
            }
            //创建列
            String TitleText,TitleName;
            float  txtWidth;
            int TxtSize,AutoZoom,Align;
            System.out.println(headJson);
            for (int i=0;i<headJson.length();i++)
                if (headJson.optJSONObject(i).has("TitleText") == true) {
                    try {
                        TitleName = headJson.optJSONObject(i).getString("TitleName");
                        TitleText = headJson.optJSONObject(i).getString("TitleText");
                        TxtSize = headJson.optJSONObject(i).getInt("TxtSize");
                        txtWidth = headJson.optJSONObject(i).getLong("TxtWidth");
                        AutoZoom = headJson.optJSONObject(i).getInt("AutoZoom");
                        TextView tv = new TextView(this);
                        tv.setText(TitleText);
                        tv.setWidth((int) txtWidth);
                        tv.setTextColor(getResources().getColor(R.color.text_main));
                        tv.setTextSize(TxtSize);
                        if (headJson.optJSONObject(i).has("Align")==true) {
                            Align = headJson.optJSONObject(i).getInt("Align");
                            switch (Align) {
                                case 0:
                                    tv.setGravity(Gravity.CENTER_VERTICAL | Gravity.LEFT);
                                    break;
                                case 1:
                                    tv.setGravity(Gravity.CENTER_VERTICAL | Gravity.CENTER_HORIZONTAL);
                                    break;
                                case 2:
                                    tv.setGravity(Gravity.CENTER_VERTICAL | Gravity.RIGHT);
                                    break;
                                default:
                                    tv.setGravity(Gravity.CENTER_VERTICAL);
                                    break;
                            }
                        }
                        //自定义文字颜色;
                        if (headJson.optJSONObject(i).has("Color")==true){
                            tv.setTextColor(GetColorValue( headJson.optJSONObject(i).getString("Color")));
                        }
                        //自定义背景颜色;
                        if (headJson.optJSONObject(i).has("TitleColor")==true){
                            tv.setBackgroundColor(GetColorValue(headJson.optJSONObject(i).getString("TitleColor")));
                        }
                        //添加到View中;
                        if (AutoZoom==1) querylisthead.addView(tv,new LinearLayout.LayoutParams((int) txtWidth, MATCH_PARENT, 1));
                        else querylisthead.addView(tv,new LinearLayout.LayoutParams((int) txtWidth, MATCH_PARENT, 0));
                        //增加间隔线
                        if (i<headJson.length()-1) {
                            View lineView = new View(this);
                            lineView.setBackgroundColor(getResources().getColor(R.color.gridLine));
                            querylisthead.addView(lineView, new LinearLayout.LayoutParams(1, MATCH_PARENT, 0));
                        }
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                }
            querylisthead.postInvalidate();
            //发消息查明细;
            Message msg = new Message();
            msg.what = MSG_GetDetail;
            handler.removeMessages(msg.what);
            handler.sendMessage(msg);
        }
    }

    //创建列;
    private void CreateDetailListHead() {
        System.out.println("CreateDetailListHead-SonTitle");
        //内容为表头，宽度，自适应;
        if ((detailHeadJson != null) && (detailHeadJson.length() > 0)) {
            int childCount = detailListhead.getChildCount();
            for (int i = childCount - 1; i >= 0; i--) {
                View view = detailListhead.getChildAt(i);
                if ((view instanceof TextView)||(view instanceof View)) {
                    detailListhead.removeViewAt(i);
                }
            }
            //创建列
            String TitleText,TitleName;
            float  txtWidth;
            int TxtSize,AutoZoom,Align;
            System.out.println(detailHeadJson);
            for (int i=0;i<detailHeadJson.length();i++)
                if (detailHeadJson.optJSONObject(i).has("TitleText") == true) {
                    try {
                        TitleName = detailHeadJson.optJSONObject(i).getString("TitleName");
                        TitleText = detailHeadJson.optJSONObject(i).getString("TitleText");
                        TxtSize = detailHeadJson.optJSONObject(i).getInt("TxtSize");
                        txtWidth = detailHeadJson.optJSONObject(i).getLong("TxtWidth");
                        AutoZoom = detailHeadJson.optJSONObject(i).getInt("AutoZoom");
                        TextView tv = new TextView(this);
                        tv.setText(TitleText);
                        tv.setWidth((int) txtWidth);
                        tv.setTextColor(getResources().getColor(R.color.text_main));
                        tv.setTextSize(TxtSize);
                        if (detailHeadJson.optJSONObject(i).has("Align")==true) {
                            Align = detailHeadJson.optJSONObject(i).getInt("Align");
                            switch (Align) {
                                case 0:
                                    tv.setGravity(Gravity.CENTER_VERTICAL | Gravity.LEFT);
                                    break;
                                case 1:
                                    tv.setGravity(Gravity.CENTER_VERTICAL | Gravity.CENTER_HORIZONTAL);
                                    break;
                                case 2:
                                    tv.setGravity(Gravity.CENTER_VERTICAL | Gravity.RIGHT);
                                    break;
                                default:
                                    tv.setGravity(Gravity.CENTER_VERTICAL);
                                    break;
                            }
                        }
                        //自定义文字颜色;
                        if (detailHeadJson.optJSONObject(i).has("Color")==true){
                            tv.setTextColor(GetColorValue( detailHeadJson.optJSONObject(i).getString("Color")));
                        }
                        //自定义背景颜色;
                        if (detailHeadJson.optJSONObject(i).has("TitleColor")==true){
                            tv.setBackgroundColor(GetColorValue(detailHeadJson.optJSONObject(i).getString("TitleColor")));
                        }
                        //添加到View中;
                        if (AutoZoom==1) detailListhead.addView(tv,new LinearLayout.LayoutParams((int) txtWidth, MATCH_PARENT, 1));
                        else detailListhead.addView(tv,new LinearLayout.LayoutParams((int) txtWidth, MATCH_PARENT, 0));

                        //增加间隔线
                        if (i<detailHeadJson.length()-1) {
                            View lineView = new View(this);
                            lineView.setBackgroundColor(getResources().getColor(R.color.gridLine));
                            detailListhead.addView(lineView, new LinearLayout.LayoutParams(1, MATCH_PARENT, 0));
                        }
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                }
            detailListhead.postInvalidate();
        }
    }
    //直接连获取数据，与Handler配套使用;
    private void ReadSQLData ( final String SQLComm,String url){
        Runnable run = new Runnable() {
            @Override
            public void run() {
                try {
                    JSONArray jsonArray;
                    if (url!=null&&url.length()>0)
                        jsonArray = DBUtil.QuerySQL2JSON(SQLComm,url);
                    else
                        jsonArray = DBUtil.QuerySQL2JSON(SQLComm);
                    System.out.println(jsonArray);
                    //往界面转数据;
                    if ((jsonArray != null) && (jsonArray.length() > 0)) {
                        if (jsonArray.optJSONObject(0).has("OperType") == true) {

                            if (jsonArray.optJSONObject(0).getString("OperType").equals("SetIdent") == true) {
                                String hint="";
                                if (jsonArray.optJSONObject(0).has("ErrInfo")) hint=jsonArray.optJSONObject(0).getString("ErrInfo");
                                if (jsonArray.optJSONObject(0).has("ResultInfo")) hint=jsonArray.optJSONObject(0).getString("ResultInfo");
                                //显示预排单;
                                Message msg = new Message();
                                msg.what = Msg_SetIdentOver;
                                Bundle bundle=new Bundle();
                                bundle.putString("HintInfo",hint);
                                msg.setData(bundle);
                                handler.removeMessages(msg.what);
                                handler.sendMessage(msg);
                                return;
                            }
                            if (jsonArray.optJSONObject(0).getString("OperType").equals("Title") == true) {
                                headJson = jsonArray;
                                //显示预排单;
                                Message msg = new Message();
                                msg.what = MSG_HeadOver;
                                handler.removeMessages(msg.what);
                                handler.sendMessage(msg);
                            }
                            //呼叫信息及库存警告
                            if (jsonArray.optJSONObject(0).getString("OperType").equals("Query") == true) {
                                masterJson = jsonArray;
                                //显示预排单;
                                Message msg = new Message();
                                msg.what = MSG_DetailOver;
                                handler.removeMessages(msg.what);
                                handler.sendMessage(msg);
                            }
                            if (jsonArray.optJSONObject(0).getString("OperType").equals("SonTitle") == true) {
                                detailHeadJson = jsonArray;
                                //显示预排单;
                                Message msg = new Message();
                                msg.what = MSG_DetailHeadOver;
                                handler.removeMessages(msg.what);
                                handler.sendMessage(msg);
                            }

                            //呼叫信息及库存警告
                            if (jsonArray.optJSONObject(0).getString("OperType").equals("SonQuery") == true) {
                                detailJson = jsonArray;
                                //显示预排单;
                                Message msg = new Message();
                                msg.what = MSG_SonDetailOver;
                                handler.removeMessages(msg.what);
                                handler.sendMessage(msg);
                            }

                        }
                        if (jsonArray.optJSONObject(0).has("SQLExcept") == true) {
                            //刷新界面;
                            Message errmsg = new Message();
                            Bundle bundle=new Bundle();
                            bundle.putString("HintInfo",jsonArray.optJSONObject(0).getString("SQLMessage"));
                            errmsg.what = MSG_ERROR;
                            errmsg.setData(bundle);
                            handler.removeMessages(errmsg.what);
                            handler.sendMessage(errmsg);
                        }
                    } else{
                        //刷新界面;
                        Message errmsg = new Message();
                        Bundle bundle=new Bundle();
                        bundle.putString("HintInfo","未返回任何数据");
                        errmsg.what = MSG_ERROR;
                        errmsg.setData(bundle);
                        handler.removeMessages(errmsg.what);
                        handler.sendMessage(errmsg);
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                    //刷新界面;
                    Message errmsg = new Message();
                    Bundle bundle=new Bundle();
                    bundle.putString("HintInfo",e.getMessage());
                    errmsg.what = MSG_ERROR;
                    errmsg.setData(bundle);
                    handler.removeMessages(errmsg.what);
                    handler.sendMessage(errmsg);
                }

            }

        };
        new Thread(run).start();

    }



    //通过消息来执行处理类程序,不更新UI则不一定需要通过这个;
    final Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            if (waitDialog.isShowing()) waitDialog.dismiss();
            // TODO Auto-generated method stub
            // 根据消息ID来判断要做的事情
            int msgId = msg.what;
            switch (msgId) {
                case Msg_SetIdentOver:
                    Bundle bundle=msg.getData();
                    String hint=bundle.getString("HintInfo","设置成功！");
                        // 创建对话框
                        AlertDialog alertDialog = new AlertDialog.Builder(QueryCutPlanActivity.this)
                                .setTitle(getString(R.string.app_name)).setMessage(hint)
                                .setPositiveButton("确认", new DialogInterface.OnClickListener() {
                                    public void onClick(DialogInterface dialog, int which) {
                                        return;
                                    }
                                }).create();
                        alertDialog.show(); // 显示对话框
                    GetSonDetail(QueryType,masterKeyValue);
                    break;
                case MSG_ERROR:
                    Bundle bundle1=msg.getData();
                    curToast.setText(bundle1.getString("HintInfo"));
                    curToast.show();
                    break;
                case MSG_HeadOver:
                    //创建列;
                    CreateListHead();
                    break;
                case MSG_DetailHeadOver:
                    CreateDetailListHead();
                    break;
                case MSG_GetDetail:
                    GetDetail(QueryType);
                    break;
                case MSG_DetailOver:
                    btn_ignore.setVisibility(View.GONE);
                    btn_cancelIgnore.setVisibility(View.GONE);
                    //显示明细数据
                    MasterListAdapter masterListAdapter =new MasterListAdapter(getApplicationContext());
                    masterList.setAdapter(masterListAdapter);
                    break;
                case MSG_SonDetailOver:
                    DetailListAdapter detailListAdapter =new DetailListAdapter(getApplicationContext());
                    detailList.setAdapter(detailListAdapter);
                    break;
                case MSG_OrderOver:
                    curToast.setText("合约获取成功!");
                    curToast.show();
                    break;
                default:
                    break;
            }
        }
    };

    //判断是否为数字
    public static boolean isNumer(String str) {
        Pattern pattern = Pattern.compile("-?[0-9]+\\.?[0-9]+");
        Matcher isNum = pattern.matcher(str);
        if (!isNum.matches()) {
            return false;
        }
        return true;
    }

    //从字符串转颜色
    private int GetColorValue(String paramColor){
        int PenColor= Color.WHITE;
        String StrPenColor=paramColor;
        if (StrPenColor.indexOf("#")==0){
            PenColor= Color.parseColor(paramColor);
        }else {
            if (isNumer(StrPenColor)) {
                int testColor = Integer.parseInt(StrPenColor);
                int red = (testColor & 0xff0000) >> 16;
                int green = (testColor & 0x00ff00) >> 8;
                int blue = (testColor & 0x0000ff);
                PenColor = Color.rgb(red, green, blue);
            } else {
                if (StrPenColor.equals("Black") == true)
                    PenColor = Color.BLACK;
                if (StrPenColor.equals("Blue") == true)
                    PenColor = Color.BLUE;
                if (StrPenColor.equals("Yellow") == true)
                    PenColor = Color.YELLOW;
                if (StrPenColor.equals("Red") == true)
                    PenColor = Color.RED;
                if (StrPenColor.equals("Green") == true)
                    PenColor = Color.GREEN;
                if (StrPenColor.equals("Gray") == true)
                    PenColor = Color.LTGRAY;
                if (StrPenColor.equals("White") == true)
                    PenColor = Color.WHITE;
            }
        }
        return PenColor;
    }

    //自定义适配器;
    public final class MasterListAdapter extends BaseAdapter {
        private LayoutInflater inflater;
        public MasterListAdapter(Context context) {
            inflater = (LayoutInflater) context
                    .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        }
        @Override
        public int getCount() {
            return masterJson.length();
        }

        @Override
        public Object getItem(int position) {
            try {
                return masterJson.get(position);
            } catch (JSONException e) {
                e.printStackTrace();
            }
            return null;
        }

        @Override
        public long getItemId(int position) {
            return position;
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            View view = inflater.inflate(R.layout.activity_cut_plan_query_listhead, null, false);
            //if (convertView == null) convertView = inflater.inflate(R.layout.activity_query_listhead, null, false);
            int pullVatListWidth=parent.getWidth();
            view.setLayoutParams(new ListView.LayoutParams(pullVatListWidth,38));
            int color = getResources().getColor(R.color.text_black);
            int backcolor = getResources().getColor(R.color.content);
            if (position%2==0) view.setBackgroundColor(backcolor);
            String tmpValue;
            try {
                Log.d("msg", "getView()a----------------------------------------------------->" + position);
                Log.d(TAG, "getView()----------------------------------------------------->" + position);
                if (masterJson.optJSONObject(position).has("ConColor") == true) {
                    tmpValue = masterJson.optJSONObject(position).getString("ConColor");
                    color=GetColorValue(tmpValue);
                }
                for (int i = 0; i < headJson.length(); i++)
                    if (headJson.optJSONObject(i).has("TitleText") == true) {
                        try {
                            String TitleName = headJson.optJSONObject(i).getString("TitleName");
                            if (masterJson.optJSONObject(position).has(TitleName)==true) tmpValue= masterJson.optJSONObject(position).getString(TitleName);
                            else tmpValue="unReturn";
                            int TxtSize = headJson.optJSONObject(i).getInt("TxtSize");
                            float txtWidth = headJson.optJSONObject(i).getLong("TxtWidth");
                            int AutoZoom = headJson.optJSONObject(i).getInt("AutoZoom");
                            TextView tv = new TextView(view.getContext());
                            tv.setText(tmpValue);
                            tv.setWidth((int) txtWidth);
                            tv.setTextColor(color);
                            tv.setGravity(Gravity.CENTER_VERTICAL);
                            if (headJson.optJSONObject(i).has("Align")==true) {
                                int Align;
                                Align = headJson.optJSONObject(i).getInt("Align");
                                switch (Align) {
                                    case 0:
                                        tv.setGravity(Gravity.CENTER_VERTICAL | Gravity.LEFT);
                                        break;
                                    case 1:
                                        tv.setGravity(Gravity.CENTER_VERTICAL | Gravity.CENTER_HORIZONTAL);
                                        break;
                                    case 2:
                                        tv.setGravity(Gravity.CENTER_VERTICAL | Gravity.RIGHT);
                                        break;
                                    default:
                                        tv.setGravity(Gravity.CENTER_VERTICAL);
                                        break;
                                }
                            }
                            if (masterJson.optJSONObject(position).has("BackColor")==true){
                                tv.setBackgroundColor(GetColorValue( masterJson.optJSONObject(position).getString("BackColor")));
                            }
                            //自定负数是红色;
                            if ((headJson.optJSONObject(i).has("NgvColor")==true)&&(headJson.optJSONObject(i).has("NgvTrans")==true)){
                                if (headJson.optJSONObject(i).getString("NgvTrans").equals("YES")&&(isNumer(tmpValue)==true)){
                                    if (Float.valueOf(tmpValue)<0) tv.setTextColor(GetColorValue(headJson.optJSONObject(i).getString("NgvColor")));
                                }
                            }
                            tv.setTextSize(TxtSize);
                            //添加到View中;
                            if (AutoZoom == 1)
                                ((LinearLayout)view).addView(tv, new LinearLayout.LayoutParams((int) txtWidth, MATCH_PARENT, 1));
                            else ((LinearLayout)view).addView(tv, new LinearLayout.LayoutParams((int) txtWidth, MATCH_PARENT, 0));
                            //增加间隔线
                            if (i<headJson.length()-1) {
                                View lineView = new View(view.getContext());
                                lineView.setBackgroundColor(getResources().getColor(R.color.gridLine));
                                ((LinearLayout)view).addView(lineView, new LinearLayout.LayoutParams(1, MATCH_PARENT, 0));
                            }
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                    }
            } catch (JSONException e) {
                e.printStackTrace();
                System.out.println(e.getMessage());
            }
            Log.d("msg","DetailListAdapter_position:"+position);
            return view;
        }
    }

    //自定义适配器;
    public final class DetailListAdapter extends BaseAdapter {
        private LayoutInflater inflater;
        public DetailListAdapter(Context context) {
            inflater = (LayoutInflater) context
                    .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        }
        @Override
        public int getCount() {
            return detailJson.length();
        }

        @Override
        public Object getItem(int position) {
            try {
                return detailJson.get(position);
            } catch (JSONException e) {
                e.printStackTrace();
            }
            return null;
        }

        @Override
        public long getItemId(int position) {
            return position;
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            View view = inflater.inflate(R.layout.activity_cutplan_query_detailhead, null, false);
            //if (convertView == null) convertView = inflater.inflate(R.layout.activity_query_listhead, null, false);
            int pullVatListWidth=parent.getWidth();
            view.setLayoutParams(new ListView.LayoutParams(pullVatListWidth,38));
            int color = getResources().getColor(R.color.text_black);
            int backcolor = getResources().getColor(R.color.content);
            //if (position%2==0) view.setBackgroundColor(backcolor);
            String tmpValue;
            try {
                Log.d("msg", "getView()a----------------------------------------------------->" + position);
                Log.d(TAG, "getView()----------------------------------------------------->" + position);
                if (detailJson.optJSONObject(position).has("ConColor") == true) {
                    tmpValue = detailJson.optJSONObject(position).getString("ConColor");
                    color=GetColorValue(tmpValue);
                }
                for (int i = 0; i < detailHeadJson.length(); i++)
                    if (detailHeadJson.optJSONObject(i).has("TitleText") == true) {
                        try {
                            String TitleName = detailHeadJson.optJSONObject(i).getString("TitleName");
                            if (detailJson.optJSONObject(position).has(TitleName)==true) tmpValue= detailJson.optJSONObject(position).getString(TitleName);
                            else tmpValue="unReturn";
                            int TxtSize = detailHeadJson.optJSONObject(i).getInt("TxtSize");
                            float txtWidth = detailHeadJson.optJSONObject(i).getLong("TxtWidth");
                            int AutoZoom = detailHeadJson.optJSONObject(i).getInt("AutoZoom");
                            TextView tv = new TextView(view.getContext());
                            tv.setText(tmpValue);
                            tv.setWidth((int) txtWidth);
                            tv.setTextColor(color);
                            tv.setGravity(Gravity.CENTER_VERTICAL);
                            if (detailHeadJson.optJSONObject(i).has("Align")==true) {
                                int Align;
                                Align = detailHeadJson.optJSONObject(i).getInt("Align");
                                switch (Align) {
                                    case 0:
                                        tv.setGravity(Gravity.CENTER_VERTICAL | Gravity.LEFT);
                                        break;
                                    case 1:
                                        tv.setGravity(Gravity.CENTER_VERTICAL | Gravity.CENTER_HORIZONTAL);
                                        break;
                                    case 2:
                                        tv.setGravity(Gravity.CENTER_VERTICAL | Gravity.RIGHT);
                                        break;
                                    default:
                                        tv.setGravity(Gravity.CENTER_VERTICAL);
                                        break;
                                }
                            }
                            //自定义文字颜色;
                            if (detailJson.optJSONObject(position).has("BackColor")==true){
                                tv.setBackgroundColor(GetColorValue( detailJson.optJSONObject(position).getString("BackColor")));
                            }
                            //自定负数是红色;
                            if ((detailHeadJson.optJSONObject(i).has("NgvColor")==true)&&(detailHeadJson.optJSONObject(i).has("NgvTrans")==true)){
                                if (detailHeadJson.optJSONObject(i).getString("NgvTrans").equals("YES")&&(isNumer(tmpValue)==true)){
                                    if (Float.valueOf(tmpValue)<0) tv.setTextColor(GetColorValue(detailHeadJson.optJSONObject(i).getString("NgvColor")));
                                }
                            }
                            tv.setTextSize(TxtSize);
                            //添加到View中;
                            if (AutoZoom == 1)
                                ((LinearLayout)view).addView(tv, new LinearLayout.LayoutParams((int) txtWidth, MATCH_PARENT, 1));
                            else ((LinearLayout)view).addView(tv, new LinearLayout.LayoutParams((int) txtWidth, MATCH_PARENT, 0));
                            //增加间隔线
                            if (i<headJson.length()-1) {
                                View lineView = new View(view.getContext());
                                lineView.setBackgroundColor(getResources().getColor(R.color.gridLine));
                                ((LinearLayout)view).addView(lineView, new LinearLayout.LayoutParams(1, MATCH_PARENT, 0));
                            }
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                    }
            } catch (JSONException e) {
                e.printStackTrace();
                System.out.println(e.getMessage());
            }
            Log.d("msg","DetailListAdapter_position:"+position);
            return view;
        }
    }

}
